package UnionFindSet;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ling
 * Date: 2022-11-27
 * Time: 20:58
 */

public class UnionFindSet {
    public int[] elem;
    public int usedSize;

    public UnionFindSet(int n) {
        this.elem = new int[n];
        Arrays.fill(elem,-1);
    }

    /**
     * 查找数据x的根节点
     * @param x
     * @return
     */
    public int findRoot(int x) {
        if(x<0) {
            throw new IndexOutOfBoundsException("下标不合法，是负数");
        }
        while(elem[x]>=0) {
            x = elem[x];
        }
        return x;
    }

    /**
     * 判断x1和x2是不是同一个集合
     * @param x1
     * @param x2
     * @return
     */
    public boolean isSameUnionFindSet(int x1,int x2) {
        int index1= findRoot(x1);
        int index2 = findRoot(x2);
        return index1==index2;
    }

    /**
     * 合并操作
     * @param x1
     * @param x2
     */
    public void union(int x1,int x2) {
        int index1 = findRoot(x1);
        int index2 = findRoot(x2);
        if(index1==index2) {
            return;
        }
        elem[index1] = elem[index1]+elem[index2];
        elem[index2] = index1;
    }

    /**
     *
     * @return
     */
    public int getCount() {
        int count =0;
        for(int x:elem) {
            if(x<0) {
                count++;
            }
        }
        return count;
    }
    public static void main(String[] args) {
        UnionFindSet unionFindSet = new UnionFindSet(10);
        unionFindSet.union(0,6);
    }
}
